		.386

		.MODEL	FLAT


		.CODE

		PUBLIC	INIT_EAX,CAPTURE_EAX,RELEASE_EAX


GLOBALSEM_STRUCT	STRUC

_SEM_ITSELF	DD	?
_SEM_COUNTER	DD	?

GLOBALSEM_STRUCT	ENDS


INIT_EAX	PROC
		;
		;EAX IS PTR TO GLOBALSEM_STRUCT
		;
		PUSH	EBX
		MOV	EBX,EAX
		ASSUME	EBX:PTR GLOBALSEM_STRUCT

		PUSH	0	;NO NAME
		PUSH	1	;MAX COUNT

		PUSH	0	;INITIAL COUNT
		PUSH	0	;NO SECURITY

		CALL	_CreateSemaphoreA

		TEST	EAX,EAX
		JZ	L9$

		MOV	[EBX]._SEM_COUNTER,-1

		MOV	[EBX]._SEM_ITSELF,EAX
		POP	EBX

		RET

L9$:
		MOV	AL,CREATESEM_ERR
		CALL	ERR_ABORT

INIT_EAX	ENDP



CAPTURE_EAX	PROC
		;
		;
		;
		ASSUME	EAX:PTR GLOBALSEM_STRUCT

		INC	[EAX]._SEM_COUNTER	;MUST BE ATOMIC
		JZ	L1$

		MOV	EAX,[EAX]._SEM_ITSELF	;HANDLE FOR THIS SEMAPHORE
		JS	L1$

		TEST	EAX,EAX			;THIS WAY IT WORKS UNDER WIN32S
		JZ	L1$

		PUSH	EDX
		PUSH	ECX

		PUSH	-1			;WAIT FOREVER
		PUSH	EAX

		CALL	_WaitForSingleObject

		POP	ECX
		POP	EDX

		INC	EAX
		JZ	L9$			;ERROR
L1$:
		RET

L9$:
		MOV	AL,_TIMEOUT_ERR
		CALL	ERR_ABORT

CAPTURE_EAX	ENDP


RELEASE_EAX	PROC
		;
		;
		;
		DEC	[EAX]._SEM_COUNTER	;MUST BE ATOMIC
		JNS	L1$

		RET

L1$:
		MOV	EAX,[EAX]._SEM_ITSELF
		PUSH	EDX

		TEST	EAX,EAX			;THIS WAY IT WORKS UNDER WIN32S
		JZ	L9$

		PUSH	ECX
		PUSH	0			;I DON'T WANT PREVIOUS COUNT

		PUSH	1			;INCREASE COUNT BY 1
		PUSH	EAX

		CALL	_ReleaseSemaphore

		POP	ECX
L9$:
		POP	EDX

		RET

RELEASE_EAX	ENDP


		END

